<?php $title = "文章"; ?>
<!DOCTYPE html>
<html>

<head>
    <?php include('css.php'); ?>
    <link href="summernote/summernote-lite.min.css" rel="stylesheet">
    <!-- 引入 Summernote 的 JavaScript 文件 -->
    <script src="summernote/jquery.min.js"></script>
    <script src="summernote/summernote-lite.min.js"></script>
    <script src="summernote/summernote-zh-CN.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#summernote').summernote({
                lang: 'zh-CN',
                height: 300,
                callbacks: {
                    onImageUpload: function(files) {
                        // 遍历上传的图片文件
                        for (let i = 0; i < files.length; i++) {
                            uploadImage(files[i]);
                        }
                    }
                }
            });

            function uploadImage(file) {
                const data = new FormData();
                data.append('image', file);

                $.ajax({
                    url: 'summernote/upload.php', // 后端处理图片上传的接口地址
                    data: data,
                    cache: false,
                    contentType: false,
                    processData: false,
                    method: 'POST',
                    type: 'POST',
                    success: function(url) {
                        // 上传成功后将图片插入到编辑器中
                        $('#summernote').summernote('insertImage', url);
                    },
                    error: function(data) {
                        console.log(data);
                        alert('图片上传失败');
                    }
                });
            }
        });
    </script>
</head>

<body>

    <?php include('nav.php'); ?>
    <div class="main-content">
        <div class="container-fluid">
            <div class="row mb-4">
                <div class="col">
                    <h1 class="page-title"><?php echo $title; ?></h1>
                    <div class="mt-3">
                        <a href="article.php?module=add_article" class="btn btn-primary">新投稿</a>
                        <a href="article.php?module=list_article" class="btn btn-primary">投稿列表</a>
                    </div>
                    <div class="mt-3 mb-3">
                        <?php
                        if (isset($_GET['module'])) {
                            $module = $_GET['module'];
                            switch ($module) {
                                case 'add_article':
                        ?>
                                    <form method="POST" action="toset.php?action=article">
                                        <div class="mb-3">
                                            <label class="form-label" for="wbtreeid">网站栏目</label>
                                            <select class="form-select" name="wbtreeid" id="wbtreeid">
                                                <?php
                                                // Assume $link is defined and the database connection is established
                                                if ($link) {
                                                    $sql = "SELECT * FROM article_menu ORDER BY wbtreeid DESC";
                                                    $stmt = mysqli_prepare($link, $sql);

                                                    if ($stmt) {
                                                        mysqli_stmt_execute($stmt);
                                                        $result = mysqli_stmt_get_result($stmt);

                                                        if ($result) {
                                                            while ($row = mysqli_fetch_array($result)) {
                                                                $wbtreeid = htmlspecialchars($row['wbtreeid']);
                                                                $menu = htmlspecialchars($row['menu']);
                                                                // Output the escaped values
                                                                echo "
                    <option value=\"$wbtreeid\">$menu</option>
                    ";
                                                            }
                                                        } else {
                                                            // Handle query execution error
                                                            echo "Error executing query: " . mysqli_error($link);
                                                        }

                                                        mysqli_stmt_close($stmt);
                                                    } else {
                                                        // Handle query preparation error
                                                        echo "Error preparing query: " . mysqli_error($link);
                                                    }

                                                    mysqli_close($link);
                                                } else {
                                                    // Handle database connection error
                                                    echo "Error connecting to the database.";
                                                }
                                                ?>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label" for="title">标题</label>
                                            <input type="type" name="title" id="title" class="form-control">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label" for="author">作者/供稿人</label>
                                            <input type="type" name="author" id="author" value="<?php echo $username; ?>" class="form-control">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label" for="url">外部链接</label>
                                            <input type="type" name="url" id="url" class="form-control">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label" for="summernote">文章内容</label>
                                            <textarea class="form-control" name="text" id="summernote"></textarea>
                                        </div>
                                        <div class="mb-3">
                                            <input type="submit" class="btn btn-primary" value="添加文章">
                                        </div>
                                    </form>
                                <?php
                                    break;

                                case 'list_article':
                                    // 分页配置
                                    $perPage = 10;
                                    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                                    $start = ($page > 1) ? ($page * $perPage) - $perPage : 0;

                                    // 获取总记录数
                                    $countSql = "SELECT COUNT(*) FROM $article";
                                    $countStmt = $link->prepare($countSql);
                                    $countStmt->execute();
                                    $total = $countStmt->get_result()->fetch_row()[0];
                                    $pages = ceil($total / $perPage);

                                    // 获取当前页数据
                                    $sql = "SELECT * FROM $article ORDER BY time DESC LIMIT ?, ?";
                                    $stmt = $link->prepare($sql);
                                    $stmt->bind_param("ii", $start, $perPage);
                                    $stmt->execute();
                                    $result = $stmt->get_result();
                                ?>
                                    <div class="container mt-4">
                                        <ul class="list-group">
                                            <?php while ($row = $result->fetch_assoc()) {
                                                $title = htmlspecialchars($row['title']);
                                                $id = $row['id'];
                                                $wbtreeid = $row['wbtreeid'];
                                                $time = date("Y-n-j H:i:s", $row['time']); ?>
                                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <h5><?php echo $title; ?></h5>
                                                        <p class="mb-1">
                                                            <?php
                                                            $content = $row['content'];
                                                            $plainText = strip_tags($content);
                                                            $truncated = mb_substr($plainText, 0, 50, 'UTF-8');
                                                            if (mb_strlen($plainText, 'UTF-8') > 50) {
                                                                $truncated .= '...';
                                                            }
                                                            echo htmlspecialchars($truncated, ENT_QUOTES, 'UTF-8');
                                                            ?>
                                                        </p>
                                                        <small class="text-muted">发布于 <?php echo $time; ?></small>
                                                    </div>
                                                    <div>
                                                        <a href="article.php?module=update_article&wbtreeid=<?php echo $wbtreeid; ?>&id=<?php echo $id; ?>" class="btn btn-primary btn-sm" onclick="window.open(this.href, '_blank', 'width=1000,height=600');return false">修改</a>
                                                        <a href="JavaScript:;" class="btn btn-danger btn-sm" data-id="<?php echo $id; ?>" onclick="confirmDelete(this)">删除</a>
                                                    </div>
                                                </li>
                                            <?php } ?>
                                        </ul>
                                        <nav aria-label="Page navigation" class="mt-3">
                                            <ul class="pagination justify-content-center">
                                                <?php if ($page > 1): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="article.php?module=list_article&page=<?= $page - 1 ?>" aria-label="Previous">
                                                            <span aria-hidden="true">&laquo;</span>
                                                        </a>
                                                    </li>
                                                <?php endif; ?>

                                                <?php for ($i = 1; $i <= $pages; $i++): ?>
                                                    <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                                                        <a class="page-link" href="article.php?module=list_article&page=<?= $i ?>"><?= $i ?></a>
                                                    </li>
                                                <?php endfor; ?>

                                                <?php if ($page < $pages): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="article.php?module=list_article&page=<?= $page + 1 ?>" aria-label="Next">
                                                            <span aria-hidden="true">&raquo;</span>
                                                        </a>
                                                    </li>
                                                <?php endif; ?>
                                            </ul>
                                        </nav>
                                    </div>

                                    <script type="text/javascript">
                                        function actionControl(actionType, id) {
                                            var xhr = new XMLHttpRequest();
                                            var requestUrl = 'toset.php?action=' + encodeURIComponent(actionType) + '&id=' + encodeURIComponent(id);
                                            xhr.open('GET', requestUrl, true);
                                            xhr.onreadystatechange = function() {
                                                if (xhr.readyState === 4) {
                                                    if (xhr.status === 200) {
                                                        location.reload();
                                                    } else {
                                                        alert('出错！状态码：' + xhr.status);
                                                    }
                                                }
                                            };
                                            xhr.send();
                                        }

                                        function confirmDelete(button) {
                                            var id = button.getAttribute('data-id');
                                            if (confirm('您确定要删除吗？')) {
                                                actionControl('delarticle', id);
                                            }
                                        }
                                    </script>
                                <?php break;

                                case 'update_article':
                                    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
                                    $wbtreeid = isset($_GET['wbtreeid']) ? (int)$_GET['wbtreeid'] : 0;
                                    $article_sql = "SELECT * FROM $article WHERE wbtreeid = ? AND id = ?";
                                    $stmt = $link->prepare($article_sql);
                                    $stmt->bind_param("ii", $wbtreeid, $id);
                                    $stmt->execute();
                                    $article_result = $stmt->get_result();
                                    $article_row = $article_result->fetch_assoc(); ?>

                                    <form method="POST" action="toset.php?action=updatearticle&id=<?php echo $article_row['id']; ?>">
                                        <div class="mb-3">
                                            <label class="form-label">网站栏目</label>
                                            <select class="form-select" name="wbtreeid">
                                                <?php $sql = "SELECT * FROM article_menu ORDER BY wbtreeid DESC";
                                                $stmt = $link->prepare($sql);
                                                $stmt->execute();
                                                $result = $stmt->get_result();
                                                while ($row = $result->fetch_assoc()) { ?>
                                                    <option value="<?php echo $row['wbtreeid']; ?>" <?php if ($row['wbtreeid'] == $article_row['wbtreeid']) echo ' selected'; ?>><?php echo htmlspecialchars($row['menu']); ?></option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">标题</label>
                                            <input type="text" name="title" value="<?php echo htmlspecialchars($article_row['title']); ?>" class="form-control">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">作者/供稿人</label>
                                            <input type="type" name="author" class="form-control" value="<?php echo htmlspecialchars($article_row['author']); ?>">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">外部链接</label>
                                            <input type="text" name="url" value="<?php echo htmlspecialchars($article_row['url']); ?>" class="form-control">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">文章内容</label>
                                            <textarea class="form-control" name="text" id="summernote"><?php echo htmlspecialchars($article_row['content']); ?></textarea>
                                        </div>
                                        <div class="mb-3">
                                            <input type="submit" class="btn btn-primary" value="修改文章">
                                        </div>
                                    </form>

                        <?php break;
                            }
                        }
                        ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php include('bottom.php'); ?>


</body>

</html>